package org.jeecg.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.StringUtils;
import org.jeecg.modules.message.entity.SysMessage;
import org.jeecg.modules.message.mapper.SysMessageMapper;
import org.jeecg.modules.system.entity.SysSms;
import org.jeecg.modules.system.mapper.SysSmsMapper;
import org.jeecg.modules.system.service.ISysSmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * @Description: 短信
 * @Author: jeecg-boot
 * @Date:   2021-02-04
 * @Version: V1.0
 */
@Service
@Slf4j
public class SysSmsServiceImpl extends ServiceImpl<SysSmsMapper, SysSms> implements ISysSmsService {
    private final String smsRules = "短信字数含\"签名+模版内容+变量内容”，短信70个字数含以内，按1条短信计费；超出70个字为长短信，按照67个字数记为1条短信费用。";

    @Autowired
    private SysSmsMapper sysSmsMapper;

    @Override
    public String queryTenantMount(String tenantId) {
        return sysSmsMapper.queryTenantMount(tenantId);
    }

    @Override
    public IPage<SysSms> findPage(Page<SysSms> page, SysSms sysSms) {
        return sysSmsMapper.findPage(page,sysSms);
    }
    public boolean addMessage(SysSms sms){
        log.info("短信保存接受参数:{}",sms);
        if (sms.getEsContent() == null){
            return false;
        }
        if (StringUtils.isEmpty(sms.getProjectId())){
            return false;
        }
        if (sms.getEsType() == null){
            return false;
        }
        if (StringUtils.isEmpty(sms.getBusinessId())){
            return false;
        }
        if (sms.getTenantId() == null){
            return false;
        }
        sms.setTenantId(sms.getTenantId());
        //查询渠道对应的短信金额
        String tAmount =  sysSmsMapper.queryTenantMount(sms.getTenantId());
        if (StringUtils.isEmpty(tAmount)){
            tAmount = "0";
        }
        BigDecimal tenantAmount = new BigDecimal(tAmount);
        BigDecimal smsAmount = BigDecimal.ZERO;
        int length = sms.getEsContent().toString().length();
        BigDecimal bLength = new BigDecimal(length);
        BigDecimal standLength = new BigDecimal(67);
        if (length >70){
            smsAmount =  (bLength.subtract(standLength)).divide(standLength).add(new BigDecimal(1)).multiply(tenantAmount) ;
        }else {
            smsAmount = tenantAmount;
        }
        sms.setPrice(tAmount);
        sms.setAmount(smsAmount.toString());
        sms.setSmsRules(smsRules);
        try {
            sysSmsMapper.insertMessage(sms);

        }catch (Exception e){
            e.printStackTrace();
        }
        return true;
    }

}
